/**
 * 
 */
package org.mhz.filetodb.main;

import java.io.File;

/**
 * @author Mahan
 *
 * 
 */
public class FolderTraversar 
{
	private String mIndent = "";
	private File mOriginalFileObject;
	private File mFileObject;
 
	private String mParentFolder = null;
	
	public FolderTraversar(final File fileObject) 
	{
		this.mOriginalFileObject = fileObject;
		this.mFileObject = fileObject;
	}
 
	public void traverse() 
	{
		recursiveTraversal(mFileObject);
	}
 
	public void recursiveTraversal(final File fileObject) 
	{
		if (fileObject.isDirectory()) 
		{
			mIndent = getIndent(fileObject);
			System.out.println(mIndent + fileObject.getName());
			File allFiles[] = fileObject.listFiles();
			
			for (File aFile : allFiles) 
			{
				recursiveTraversal(aFile);
			}
		} 
		else if (fileObject.isFile()) 
		{
			System.out.println(mIndent + " " + fileObject.getName());
		}
	}
 
	protected String getIndent(final File fileObject) 
	{
		String original = mOriginalFileObject.getAbsolutePath();		
		String fileStr = fileObject.getAbsolutePath();
		String subString = fileStr.substring(original.length(),
				fileStr.length());
		String indent = "";
		
		final String[] folderHierarchy = subString.split("\\\\");
		
		if ((folderHierarchy != null) && (folderHierarchy.length > 2))
		{
		    mParentFolder = getModifiedName(folderHierarchy[folderHierarchy.length - 2]);
		}
		else
		{
		    final String[] outerFolderHierarchy = original.split("\\\\");
		    mParentFolder = getModifiedName(outerFolderHierarchy[outerFolderHierarchy.length - 1]);
		}
		
		for (int index = 0; index < subString.length(); index++) 
		{
			char aChar = subString.charAt(index);
			if (aChar == File.separatorChar) 
			{
				indent = indent + "\t";
			}
		}
		return indent;
	}

    protected static String getModifiedName(final String aName)
    {
        String modifiedName = aName.toLowerCase();
        
        modifiedName = modifiedName.replaceAll(". ", "_");
        modifiedName = modifiedName.replaceAll("'", "");
        modifiedName = modifiedName.replaceAll(", ", "_");
        modifiedName = modifiedName.replaceAll(",", "_");
        modifiedName = modifiedName.replaceAll(" - ", "_");
        modifiedName = modifiedName.replaceAll("-", "_");
        modifiedName = modifiedName.replaceAll(" ", "_");        
        
        return modifiedName;
    }
    
    /**
     * @return Returns the parentFolder.
     */
    public String getParentFolder()
    {
        return mParentFolder;
    }

    /**
     * @param aParentFolder The parentFolder to set.
     */
    public void setParentFolder(String aParentFolder)
    {
        mParentFolder = aParentFolder;
    }		
}
